package com.example.job.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


import androidx.annotation.Nullable;

import com.example.job.entity.UserInfo;

public class userdb extends SQLiteOpenHelper {
    private static userdb sHelper;
    private static final String DB_NAME = "user.db";   //数据库名
    private static final int VERSION = 1;    //版本号

    //必须实现其中一个构方法
    public userdb(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
    //创建单例，供使用调用该类里面的的增删改查的方法
    public synchronized static userdb getInstance(Context context) {
        if (null == sHelper) {
            sHelper = new userdb(context, DB_NAME, null, VERSION);
        }
        return sHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建user_table表
        String CREATE_TABLE = "create table user_table(" +
                "user_id integer primary key autoincrement, " +
                "username text, " +       //用户名
                "password text, " +       //密码
                "job_id text)";           //职位id
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            // 添加 job_id 字段
            db.execSQL("ALTER TABLE user_table ADD COLUMN job_id INTEGER DEFAULT -1");
        }
    }

    @SuppressLint("Range")
    public UserInfo getUserInfoByUsername(String username) {
        SQLiteDatabase db = getReadableDatabase();
        UserInfo userInfo = null;
        String sql = "select user_id, username, password, job_id from user_table where username=?"; // 添加 job_id
        String[] selectionArgs = {username};
        Cursor cursor = db.rawQuery(sql, selectionArgs);
        if (cursor.moveToNext()) {
            int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            String name = cursor.getString(cursor.getColumnIndex("username"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            String job_id = cursor.getString(cursor.getColumnIndex("job_id")); // 获取 job_id
            userInfo = new UserInfo(user_id, name, password, job_id); // 使用新的构造函数
        }
        cursor.close();
        return userInfo;
    }


//    登录
    @SuppressLint("Range")
    public UserInfo login(String username) {
        //获取SQLiteDatabase实例
        SQLiteDatabase db = getReadableDatabase();
        UserInfo userInfo = null;
        String sql = "select user_id,username,password  from user_table where username=?";
        String[] selectionArgs = {username};
        Cursor cursor = db.rawQuery(sql, selectionArgs);
        if (cursor.moveToNext()) {
            int user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
            String name = cursor.getString(cursor.getColumnIndex("username"));
            String password = cursor.getString(cursor.getColumnIndex("password"));
            userInfo = new UserInfo(user_id, name, password);
        }
        cursor.close();
        db.close();
        return userInfo;
    }

//注册
    @SuppressLint("Range")
    public long register(String username, String password) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username", username);
        values.put("password", password);
        long result = db.insert("user_table", null, values);
        db.close();
        return result;
    }

    //更新密码
    @SuppressLint("Range")
    public long update(int user_id, String password) {
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("password", password);
        int update = db.update("user_table", values, "user_id=?", new String[]{String.valueOf(user_id)});
        db.close();
        return update;
    }

    //添加收藏
    @SuppressLint("Range")
    public long updateJobId(int user_id, String newJobId) {
        SQLiteDatabase db = getWritableDatabase();
        String currentJobId = getCurrentJobId(user_id);
        Log.d("syj", "1: newJobId=" + newJobId + ", job_id=" + currentJobId);

        // 将 currentJobId 按照逗号分割成数组
        String[] jobIdArray = currentJobId.split(",");

        // 检查 newJobId 是否存在于数组中
        boolean newJobIdExists = false;
        for (String jobId : jobIdArray) {
            if (jobId.equals(newJobId)) {
                newJobIdExists = true;
                break;
            }
        }

        if (!newJobIdExists) {
            String updatedJobId = currentJobId + (currentJobId.isEmpty() ? "" : ",") + newJobId;
            ContentValues values = new ContentValues();
            values.put("job_id", updatedJobId);
            int update;
            try {
                db.beginTransaction();
                update = db.update("user_table", values, "user_id=?", new String[]{String.valueOf(user_id)});
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
                db.close();
            }
            if (update > 0) {
                // 更新成功
                Log.d("syj", "1: user_id=" + user_id + ", job_id=" + updatedJobId);
            } else {
                // 更新失败
                Log.e("syj", "2: user_id=" + user_id + ", job_id=" + updatedJobId);
            }
            return update;
        } else {
            Log.d("syj", "2: newJobId already exists in currentJobId");
        }
        return 0;
    }


    @SuppressLint("Range")
    private String getCurrentJobId(int user_id) {
        SQLiteDatabase db = getReadableDatabase();
        String sql = "SELECT job_id FROM user_table WHERE user_id = ?";
        String[] selectionArgs = {String.valueOf(user_id)};
        Cursor cursor = db.rawQuery(sql, selectionArgs);
        String currentJobId = "";
        if (cursor.moveToFirst()) {
            currentJobId = cursor.getString(cursor.getColumnIndex("job_id"));
        }
        cursor.close();
        return currentJobId;
    }


    //删除表
    public void dropAndRecreateUserTable() {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("DROP TABLE IF EXISTS user_table");
        onCreate(db);
        db.close();
    }

}

